package com.xiaoc.bulldozer.job;

import com.xc.framework.common.job.AbstractParallelJob;
import com.xiaoc.bulldozer.common.Constant;
import com.xiaoc.bulldozer.common.model.Award;
import com.xiaoc.bulldozer.common.service.AwardService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * describe:
 *
 * @author lihuancheng
 * @date 2018/9/3
 */
@Component
@EnableScheduling
@Transactional(rollbackFor = Throwable.class)
public class AwardStatusJob extends AbstractParallelJob {

    private Logger logger = LoggerFactory.getLogger(AwardStatusJob.class);

    @Resource(name = "awardService")
    private AwardService awardService;


    @Override
    public String getJobName() {
        return "AwardStatusJob";
    }

    /**
     * 每1分钟执行一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void run() {
        super.run();
    }

    @Override
    public void execute() {

        updateAwardStatus();
    }

    /**
     * 把根据结束时间，红包状态改为 红包过期结束
     */
    private void updateAwardStatus() {

        List<Award> awardList = awardService.getAwardListByStatus(Constant.ENABLE);

        if (CollectionUtils.isNotEmpty(awardList)) {

            Set<Integer> awardIds = new TreeSet<>();

            long currentTime = System.currentTimeMillis();

            for (Award award : awardList) {

                if (NumberUtils.compare(award.getEndTime(), currentTime) < 0) {
                    awardIds.add(award.getId());
                }
            }

            //如果id集合不为空，根据id集合更改状态
            if (CollectionUtils.isNotEmpty(awardIds)) {
                awardService.updateStatusByIds(Constant.DISABLE, awardIds);
            }
        }

    }
}
